//
//  MessageViewController.m
//  BaseAPP
//
//  Created by Evisu on 16/12/18.
//  Copyright © 2016年 evisum. All rights reserved.
//

#import "MessageViewController.h"
#import "DMMessageCell.h"
#import "TextMessageView.h"
#import "ToolInputView.h"
#import "TZImagePickerController.h"
#import "UIImage+Extension.h"
#import "DMMessageModel.h"

@interface MessageViewController ()<UITableViewDataSource, UITableViewDelegate, DMMessageCellDelegate,ToolInputViewDelegate, TZImagePickerControllerDelegate>

@property (nonatomic, strong)UITableView *tableView;

//消息数组
@property (nonatomic, strong)NSMutableArray *messages;

//底部输入View
@property (nonatomic, strong)ToolInputView *toolView;

@end

@implementation MessageViewController

#pragma mark - 懒加载
- (NSMutableArray *)messages {

    if (!_messages) {
        
        _messages = [NSMutableArray array];
    }
    
    return _messages;
}

- (UIView *)toolView {

    if (!_toolView) {
        
        _toolView = [[ToolInputView alloc] init];
        _toolView.delegate = self;
    }
    
    return _toolView;
}

#pragma mark -
- (void)viewDidLoad {

    [super viewDidLoad];
    
    [self initViews];
    [self layoutViews];

    //获取消息列表
    [self.conversation loadMessagesStartFromId:nil count:20 searchDirection:EMMessageSearchDirectionUp completion:^(NSArray *aMessages, EMError *aError) {
        DMLog(@"%@",[NSThread currentThread]);
        
        for (EMMessage *message in aMessages) {
            
            //模型转换
            DMMessageModel *messageModel = [[DMMessageModel alloc] init];
            messageModel.message = message;
            
            //高度自适应的模型
            DMMessageCellModel *cellModel = [[DMMessageCellModel alloc] init];
            cellModel.message = messageModel;
            [self.messages addObject:cellModel];
        }
        
        [self.tableView reloadData];
        
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messages.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }];
    
}

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    
    //键盘通知
    [BaseNotificationCenter addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    //加号通知
    [BaseNotificationCenter addObserver:self selector:@selector(didClickedShareMore:) name:KSHARE_MORE object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {

    [super viewWillDisappear:animated];
    
    
    [BaseNotificationCenter removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    
    [BaseNotificationCenter removeObserver:self name:KSHARE_MORE object:nil];
}



#pragma mark - 视图初始化
- (void)initViews {

    self.title = self.conversation.conversationId;
    
    self.tableView = [[UITableView alloc] init];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellAccessoryNone;
    self.tableView.backgroundColor = HEXColor(@"ebebeb");
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, KTABBAR_HEIGHT, 0);
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapBlank)];
    [self.tableView addGestureRecognizer:tap];
    
    //底部输入工具栏
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.toolView];
    
}

- (void)layoutViews {
    
    self.tableView.sd_layout
    .topSpaceToView(self.view, KSTATUS_AND_NAVIGATION_HEIGHT)
    .leftEqualToView(self.view)
    .rightEqualToView(self.view)
    .bottomEqualToView(self.view);
    
    self.toolView.sd_layout
    .leftEqualToView(self.view)
    .bottomEqualToView(self.view)
    .widthRatioToView(self.view, 1)
    .heightIs(KTABBAR_HEIGHT+self.toolView.tabViewHeight);
}

#pragma mark - tableView Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    DMMessageCellModel *cellModel = self.messages[indexPath.row];
    
    return cellModel.maxCellHeight;
}


#pragma mark - table DataSources

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.messages.count;
}

- (DMMessageCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *reusedId = @"message";
    
    DMMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:reusedId];
    
    if (!cell) {
        
        cell = [[DMMessageCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusedId];
        cell.tapDelegate = self;
        
    }
    
    DMMessageCellModel *cellModel = self.messages[indexPath.row];

    cell.cellModel = cellModel;
    
    return cell;
}

#pragma mark 滑动tableView的时候关闭底部扩展View
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    if (self.toolView.btnEmotion.selected || self.toolView.btnMore.selected || [self.toolView.tvInputView isFirstResponder]) {
        
        [self.toolView hideTabView];
        [self toolInputViewDidClickedEmotion:self.toolView.btnEmotion];
    } else {
    
        [self.toolView hideTabView];
    }
}


#pragma mark - 点击头像、消息、空白地方代理
/**
 *  点击cell中空白地方收起键盘
 */
- (void)messageCellDidTapBlank {
    
    if (self.toolView.tabViewHeight == 0)   return;
    
    [self.toolView hideTabView];
    [self toolInputViewDidClickedEmotion:self.toolView.btnEmotion];
}

/**
 *  点击tableView中非cell的空白地方收起键盘
 */
- (void)didTapBlank {
    
    [self.toolView hideTabView];
    [self toolInputViewDidClickedEmotion:self.toolView.btnEmotion];
}

#pragma mark - 键盘弹出
- (void)keyboardWillShow:(NSNotification *)notification {
    
    //改变tableView内容的内边距
    //    [self resizeTableViewContentInsets];
    if (self.messages.count < 1) return ;
    
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, CGRectGetHeight(self.toolView.frame), 0);
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messages.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

#pragma mark 调整tableView的内边距
- (void)resizeTableViewContentInsets {
    
    if (self.messages.count < 1) return ;
    
    [UIView animateWithDuration:0.25 animations:^{
        
        self.tableView.contentInset = UIEdgeInsetsMake(0, 0, CGRectGetHeight(self.toolView.frame), 0);
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messages.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }];
}

#pragma mark - 底部栏代理
#pragma mark 发送消息
- (void)toolInputViewDidClickedSend:(NSString *)text {
    
    if (![text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]].length) {
    
        //判空
        [MBProgressHUD showError:@"不能发送空白消息" toView:self.view];
        return;
    };
    
    //构造消息实体
    EMTextMessageBody *body = [[EMTextMessageBody alloc] initWithText:text];
    NSString *from = [[EMClient sharedClient] currentUsername];

    //生成Message
    EMMessage *message = [[EMMessage alloc] initWithConversationID:self.conversation.conversationId from:from to:self.conversation.conversationId body:body ext:nil];
    
    [[EMClient sharedClient].chatManager sendMessage:message progress:^(int progress) {
        
        
    } completion:^(EMMessage *message, EMError *error) {
        
        if (!error.code) {

            DMLog(@"发送成功");
            
            DMMessageModel *messageModel = [[DMMessageModel alloc] init];
            messageModel.message = message;

            DMMessageCellModel *cellModel = [[DMMessageCellModel alloc] init];
            cellModel.message = messageModel;
            [self.messages addObject:cellModel];
            [self.tableView reloadData];

            //还原底部栏输入样式
            [self.toolView showOriginalTextView];
        
            [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messages.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];

        } else {
        
            [MBProgressHUD showError:error.errorDescription toView:self.view];
        }
    }];
}

#pragma mark 文字输入
- (void)toolInputViewEditing {

    [self resizeTableViewContentInsets];
}

#pragma mark 点击语音按钮代理
- (void)toolInputViewDidClickedVoice:(UIButton *)btn {

    if (self.tableView.contentSize.height-self.tableView.contentOffset.y <= self.tableView.height_sd) {
        DMLog(@"到底");
        
        //当tableView已经滑动到底部，点击语音按钮就调整tableView的内间距
        [self resizeTableViewContentInsets];
    }
}

#pragma mark 点击表情按钮代理
- (void)toolInputViewDidClickedEmotion:(UIButton *)btn {

    [UIView animateWithDuration:0.25 animations:^{
        
        [self resizeTableViewContentInsets];
    }];
}

#pragma mark 点击加号按钮代理
- (void)toolInputViewDidClickedMore:(UIButton *)btn {
    
    [UIView animateWithDuration:0.25 animations:^{
        
        [self resizeTableViewContentInsets];
    }];
}

#pragma mark 点击加号里面选项的通知
- (void)didClickedShareMore:(NSNotification *)notification {
    
    switch ([notification.userInfo[KSHARE_MORE] intValue]) {
        case ShareMore_pic:
            DMLog(@"照片");
            [self showImagePickerView];
            break;
        case ShareMore_video:
            DMLog(@"拍摄");
            break;
        case ShareMore_videovoip:
            DMLog(@"视频聊天");
            break;
        case ShareMore_location:
            DMLog(@"位置");
            break;
        case ShareMore_redbag:
            DMLog(@"红包");
            break;
        case ShareMore_pay:
            DMLog(@"转账");
            break;
        case ShareMore_friendcard:
            DMLog(@"个人名片");
            break;
        case ShareMore_wallet:
            DMLog(@"卡券");
            break;
        default:
            break;
    }
}


- (void)showImagePickerView {

    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
    
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosWithInfosHandle:^(NSArray<UIImage *> *photos,NSArray *assets,BOOL isSelectOriginalPhoto,NSArray<NSDictionary *> *infos){
        
        for (int i =0 ; i< photos.count; i++) {
            
            UIImage *image = photos[i];
            image = [image compressImage];
            
            //上传到服务器的图片
            NSData *data = [image compressImageByQuality];
            
            //保存到本地的缩略图
            NSData *thumdata = UIImageJPEGRepresentation(image, 0.1);
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *thumlocaImagePath = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:[NSString stringWithFormat:@"thumimage_%d%@.png",i,str]];
            [thumdata writeToFile:thumlocaImagePath atomically:YES];
            
            EMImageMessageBody *body = [[EMImageMessageBody alloc]initWithData:data displayName:@"image.png"];
            body.thumbnailLocalPath = thumlocaImagePath;
            body.thumbnailSize = [UIImage imageWithData:thumdata].size;
            
            NSString *from = [[EMClient sharedClient] currentUsername];
            //生成Message
            EMMessage *message = [[EMMessage alloc] initWithConversationID:self.conversation.conversationId from:from to:self.conversation.conversationId body:body ext:nil];
            message.chatType = EMChatTypeChat;// 设置为单聊消息
            [[EMClient sharedClient].chatManager sendMessage:message progress:nil completion:^(EMMessage *aMessage, EMError *aError) {
                
                if (!aError.code) {
                    
                    DMLog(@"发送成功");
                    
                    //模型转换
                    DMMessageModel *messageModel = [[DMMessageModel alloc] init];
                    messageModel.message = message;
                    
                    //高度自适应的模型
                    DMMessageCellModel *cellModel = [[DMMessageCellModel alloc] init];
                    cellModel.message = messageModel;
                    [self.messages addObject:cellModel];
                    [self.tableView reloadData];
                    
                    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messages.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
                    
                } else {
                    
                    [MBProgressHUD showError:aError.errorDescription toView:self.view];
                }
            }];
        }
    }];
    
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}



@end
